﻿@page "/users/index"
@attribute [Authorize(Policy = nameof(ApiRoutes.User.QueryUsers))]

@inject IUserService UserService
@inject ExampleJsInterop JsInterop
@inject IJSRuntime JsRuntime
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IAuthorizationService AuthorizationService
@inject DialogService DialogService


<RadzenCard Variant="Variant.Filled" Style="height : 100%;">
    <RadzenStack>

        <SearchFormPartial Model="_searchRequestDto" QueryHandler="QueryHandler"></SearchFormPartial>

        <SearchTablePartial @ref="_requestTable" T="UserInfoResponseDto" ServerData="ServerReload"
                            SearchPartial="_searchPartial" AddHandler="AddHandler" EditHandler="EditHandler"
                            ImportExcelHandler="ImportExcelHandler">
        </SearchTablePartial>

    </RadzenStack>

</RadzenCard>

@code {

    private readonly UserSearchRequestDto _searchRequestDto = new();
    private IEnumerable<UserInfoResponseDto> _pagedData = new List<UserInfoResponseDto>();
    private readonly SearchPartialInfo _searchPartial = new();
    private SearchTablePartial<UserInfoResponseDto> _requestTable = new();
    private int _totalItems;

    async Task QueryHandler(MouseEventArgs args)
    {
        await _requestTable.ReloadServerData();
    }

    async Task AddHandler(MouseEventArgs args)
    {
        await DialogService.OpenAsync<UserEdit>("Add User");
        await _requestTable.ReloadServerData();
    }

    async Task EditHandler(MouseEventArgs args, UserInfoResponseDto context)
    {
        await DialogService.OpenAsync<UserEdit>("Edit User", new Dictionary<string, object> { { "Key", context.Key } });
        await _requestTable.ReloadServerData();
    }

    async Task ImportExcelHandler(MouseEventArgs args)
    {
        await DialogService.OpenAsync<UserImport>("Import User");
        await _requestTable.ReloadServerData();
    }

    // async Task ExportClick()
    // {
    //     var response = await UserService.ExportUsers(_searchRequestDto);
    //     var fileName = HttpResponseMessageHelper.GetFileName(response);
    //     var stream = await response.Content.ReadAsStreamAsync();
    //     await JsInterop.DownloadFileFromStream(stream, fileName);
    // }

    /// <summary>
    /// Here we simulate getting the paged, filtered and ordered data from the server
    /// </summary>
    private async Task<ODataServiceResult<UserInfoResponseDto>> ServerReload(LoadDataArgs state)
    {
        if (state.Skip != null) _searchRequestDto.Page = (int)(state.Skip + 1);
        if (state.Top != null) _searchRequestDto.Limit = (int)state.Top;
        var data = await UserService.QueryUsersByPage(_searchRequestDto);

        if (data != null)
        {
            _pagedData = data.Data;
            _totalItems = data.TotalCount;
        }

        return new ODataServiceResult<UserInfoResponseDto>() { Count = _totalItems, Value = _pagedData };
    }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        _searchPartial.IsAdd = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.User.CreateUser))).Succeeded;
        _searchPartial.IsEdit = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.User.UpdateUser))).Succeeded;
        _searchPartial.IsDelete = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.User.DeleteUser))).Succeeded;
        _searchPartial.IsImportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.User.ImportUser))).Succeeded;
        _searchPartial.IsExportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.User.ExportUser))).Succeeded;
    }

}